<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<c:url value="/" var="baseUrl" />
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="img/favicon.png">
<title>数据导入</title>
<%@include file="../include/css.jsp"%>

<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>  
<script>
var ctx = "<%=request.getContextPath()%>";
console.log(ctx);

function delbs() {
	var r = confirm('确实要删除本账户所有basLog信息?');
	if (r == true) {
		$.ajax({
			type: "get",
			url: "DelBasLog",
			dataType: "text",  
	        success: function(msg) {
	        	   alert(msg);
	        }
		});
	}
}

function importArrayDocId(arrayId) {
    document.getElementById('dropbox').style.display='none';
    // console.log(arrayId);
    $("#importDataResult").empty();
    document.getElementById('light').style.display='block';
    document.getElementById('fade').style.display='block';
    var closeDiv = document.getElementById('closeDiv');
    closeDiv.style.visibility = "hidden";
    var importData = document.getElementById('importData');
    if(arrayId.length == 0) {
        importData.innerHTML = "无文件上传";
        var closeDiv = document.getElementById('closeDiv');
        closeDiv.style.visibility = "visible";
    } else {
    importData.innerHTML = "导入过程中请勿刷新";
    
    for(var docCount = 0; docCount < arrayId.length; docCount++) {
        var docId = arrayId[docCount];
        if(docId == 0) {
            continue;
        } else {
            importByDocId(docId, arrayId, docCount);
            break;
        }   
    }
    }
}

function importByDocId(docId, arrayId, docCount) {
	console.log(docId);
	var url = "ImportDocToDatabase?id=" + docId;
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			var closeDiv = document.getElementById('closeDiv');
			closeDiv.style.visibility = "visible";
			if (xmlhttp.status == 200) {
		        $("#importDataResult").append("<br/>" + xmlhttp.responseText);
		        clearInterval(timer);
		        document.getElementById('importDataCount').style.visibility = "hidden";
		        docCount++;
		        for( ; docCount < arrayId.length; docCount++) {
		            docId = arrayId[docCount];
		            if(docId == 0) {
		                continue;
		            } else {
		                importByDocId(docId, arrayId, docCount);
		                break;
		            }
		        }
			}
		}
	}
	xmlhttp.open("GET", url, true);
    xmlhttp.send();
    
    var timer = setInterval(function () {
        var importDataCount = document.getElementById('importDataCount');
        var xmlhttpRead = new XMLHttpRequest();
        xmlhttpRead.onreadystatechange = function() {
            if (xmlhttpRead.readyState == 4 && xmlhttpRead.status == 200) {
                importDataCount.style.visibility = "visible";
                importDataCount.innerHTML = "已导入" + xmlhttpRead.responseText + "条记录";
            }
        };
        xmlhttpRead.open("GET", "ReadImportedDataBase", true);
        xmlhttpRead.send();
    }, 1000);
}

function showPopup(docId) {
    document.getElementById('light').style.display='block';
    document.getElementById('fade').style.display='block';
    var closeDiv = document.getElementById('closeDiv');
    closeDiv.style.visibility = "hidden";
    var importData = document.getElementById('importData');

    importData.innerHTML = "导入过程中请勿刷新";
    var url = "ImportDocToDatabase?id=" + docId;
    var xmlhttp = new XMLHttpRequest();
    
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
           closeDiv.style.visibility = "visible";
           $("#importDataResult").append("<br/>" + xmlhttp.responseText);
           //importData.innerHTML = xmlhttp.responseText;
           clearInterval(timer);
           document.getElementById('importDataCount').style.visibility = "hidden";
        } else if(xmlhttp.readyState == 4) {
           closeDiv.style.visibility = "visible";
        }
    }

    xmlhttp.open("GET", url, true);
    xmlhttp.send();

    var timer = setInterval(function () {
        var importDataCount = document.getElementById('importDataCount');
        var xmlhttpRead = new XMLHttpRequest();
        xmlhttpRead.onreadystatechange = function() {
            if (xmlhttpRead.readyState == 4 && xmlhttpRead.status == 200) {
                  importDataCount.style.visibility = "visible";
                importDataCount.innerHTML = "已导入" + xmlhttpRead.responseText + "条记录";
            }
        };
        xmlhttpRead.open("GET", "ReadImportedDataBase", true);
        xmlhttpRead.send();
    }, 1000);
}

function disp_confirm(docId, docStatus) {
    if (docStatus == 2) {
      var r = confirm("文件已导入数据库，确定重新导入吗？");
      if (r==true) {
        showPopup(docId);
      } else {
      
      }
    } else {
        showPopup(docId);
    }
}

//文件上传函数开始


function showUploadPopup () {
    document.getElementById('dropbox').style.display='block';
    document.getElementById('fade').style.display='block';
    var dropbox = document.getElementById("dropbox");
    dropbox.addEventListener("dragenter", noop, false);
    dropbox.addEventListener("dragexit", noop, false);
    dropbox.addEventListener("dragover", noop, false);
    dropbox.addEventListener("drop", dropUpload, false);
    
    // $upst = $("#uploadStatus");
    // $upst.empty();
    upfile = 0;
    uploadDocId = new Array();
    $("#uploadProcess").empty();
    $("#uploadFileList").empty();
    $("#uploadProcess").empty();
}

function noop(event) {
    event.stopPropagation();
    event.preventDefault();
}

function dropUpload(event) {
    noop(event);
    var files = event.dataTransfer.files;
    for (var i = 0; i < files.length; i++) {
       upload(files[i]);
    }
}

function upload(file) {
    $("#uploadFileList").append('<li class="li-tag">' + file.name  +'</li>');
    var formData = new FormData();
    formData.append("file", file);

    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    <c:url value="/front/UploadDoc" var="uploadUrl" />
    xhr.open("POST", "${uploadUrl}", true); // If async=false, then you'll miss progress bar support.
    xhr.send(formData);
}

function uploadProgress(event) {
    // Note: doesn't work with async=false.
    var progress = Math.round(event.loaded / event.total * 100);
    $("#uploadProcess").text("文件进度：" + progress + "%");
    
}

function uploadComplete(event) {
	var result = JSON.parse(event.target.responseText);
	uploadDocId[upfile] = result.docId;
	upfile++;
    $("#uploadResults").append('<li>' + result.fileName + "文件上传成功" +'</li>');
}
// 文件上传函数结束

</script>

<style>
  .black_overlay{
    display: none;
    position: absolute;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    background-color: black;
    z-index:1001;
    opacity:.80;
    filter: alpha(opacity=80);
  }
  .white_content {
    display: none;
    position: absolute;
    top: 25%;
    left: 25%;
    width: 50%;
    height: 50%;
    padding: 16px;
    background-color: white;
    z-index:1002;
    overflow: auto;
  }
  #dropbox {
    border: 1px solid gray;
    border-radius: 5px;
    padding: 5px;
    color: gray;
  }
</style>

</head>
<body>


  <!-- container section start -->
  <section id="container" class="">
     
      <%@include file="../include/header.jsp"%>
        <%@include file="../include/sidebar.jsp"%>
     
      <!--sidebar end-->
     <!--main content start-->
      <section id="main-content">
          <section class="wrapper">            
              <!--overview start-->
    <c:url value="/front/ListDoc" var="url" />
    <form action="${url}" method="post">

    <div class="row">
      <div class="col-lg-12">
        <section class="panel">
          <header class="panel-heading" align="center">
                文档列表&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                （提示：导入新BASlog前请清空原有BASlog数据）
          </header>
                          
          <table class="table table-striped table-advance table-hover">
             <tbody>
            <tr>
                <th>名称</th>
                <th>时间</th>
                <th>状态</th>
                <td><a class="btn btn-success" href="javascript:void(0)" onclick="showUploadPopup()">
                    上传文件
                    </a>
                    &nbsp;&nbsp;
                    <a  class="btn btn-success" href="javascript:void(0)" 
                        onclick="delbs()">
                        清空BASlog
                    </a>  
                </td>
            </tr>
            <c:forEach items="${paging.datas}" var="doc" varStatus="status">
                <tr>
                    <td>${doc.name}</td>
                    <td>${doc.uploadedTime}</td>
                    <c:if test="${doc.status == 0}">
                       <td>未导入</td>
                    </c:if>
                    <c:if test="${doc.status == 1}">
                       <td>导入中</td>
                    </c:if>
                    <c:if test="${doc.status == 2}">
                      <td> <span class="btn-success">已导入</span></td>
                    </c:if>
                    <c:if test="${doc.status == 3}">
                       <td>无文件</td>
                    </c:if>
                    
                    <td>
                    <!-- 
                    <a href="ImportDocToDatabase?id=${doc.id}">导入</a>
                    -->
                    <a class="btn btn-primary" href="javascript:void(0)" onclick="disp_confirm(${doc.id}, ${doc.status})">导入</a>
                    <a class="btn btn-danger" href="DelDoc?id=${doc.id}"
                       onClick="return confirm('确实要删除文档 ${doc.name}');">
                       删除
                    </a>
                               
                    </td>
                </tr>
            </c:forEach>
            </tbody>
        </table>
        </section>
        </div>
        </div>
        <table align="center">
            <tr>
                <c:if test="${paging.pageCount>1}">
                    <td><input type="submit" value="首页" name="firstPage" /></td>
                </c:if>
                <c:if test="${paging.pageNo>0 && paging.pageNo<=paging.pageCount-1}">
                    <td><input type="submit" value="前页" name="previousPage" /></td>
                </c:if>
                <td>第${paging.pageNo+1}页 / 共${paging.pageCount}页</td>
                <c:if test="${paging.pageNo>=0 && paging.pageNo<paging.pageCount-1}">
                    <td><input type="submit" value="后页" name="nextPage" /></td>
                </c:if>
                <c:if test="${paging.pageCount>1}">
                    <td><input type="submit" value="尾页" name="lastPage" /></td>
                </c:if>
            </tr>
        </table>
    </form>
       </section>
      </section>
      <!--main content end-->
</section>
  <!-- container section start -->
    
    <br>
    <div id="dropbox" class="white_content" style=" text-align: center">
       请把需要导入的文件拖进来
       <div id="uploadStatus">
         <div id="uploadProcess"></div>
         <ol id="uploadFileList"></ol>
         <ul id="uploadResults"></ul>
       </div>
       <br><br><br><br><br>
       <div>
            <a class="btn btn-success" href="javascript:void(0)" onclick="importArrayDocId(uploadDocId)">
                将以上文件导入到数据库
            </a>
        </div>
        <br>
       <div>
       <a class="btn btn-success"  href="javascript:void(0)" onclick="location.reload(true)">
         关闭
       </a>
       </div>
    </div>
    <div id="light" class="white_content">
        <div id="importData"></div>
        <div id="importDataResult"></div>
        <div id="importDataCount"></div>
        <div id="closeDiv">
            <a href="javascript:void(0)" onclick="location.reload(true)">
                关闭
            </a>
        </div>
    </div>
    <div id="fade" class="black_overlay">
    </div>
    
   <%@include file="../include/scripts.jsp"%> 
<script>
$("#sidebarMyChart").removeClass('active');
$("#sidebarListSameMac").removeClass('active');
$("#sidebarListAvgFlow").removeClass('active');
$("#sidebarScatter").removeClass('active');
$("#sidebarListSigData").removeClass('active');
$("#sidebarListTop10").removeClass('active');
$("#sidebarListAccount").removeClass('active');
$("#sidebarBWListAdmin").removeClass('active');
$("#sidebarListDoc").addClass('active');
$("#sidebarListUser").removeClass('active');
</script>
</body>
</html>